package org.example.service;

import lombok.extern.slf4j.Slf4j;
import org.example.dao.BookDaoImp;
import org.example.dao.BorrowDaoImp;
import org.example.model.book;
import org.example.model.borrow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class BorrowServiceImp implements BorrowService {
    private static int borrowNum = 5;
    @Autowired
    private BorrowDaoImp borrowDaoImp;
    @Autowired
    private BookDaoImp bookDaoImp;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public boolean borrowBook(book book, String user_id) {
        if (!bookDaoImp.isExistById(book.getId())) return false;
        borrowDaoImp.borrowBook(
                new borrow(String.format("%10d", borrowNum++),
                        user_id, book.getId()));
        return true;
    }
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public boolean returnBook(String borrow_id) {
        borrow borrow = borrowDaoImp.queryById(borrow_id);
        if (borrow == null || borrow.getReturn_date() != null) return false;
        borrowDaoImp.returnBook(borrow);
        return false;
    }
    @Override
    public borrow queryById(String borrow_id) {
        return borrowDaoImp.queryById(borrow_id);
    }
    @Override
    public borrow[] queryAll() {
        return borrowDaoImp.queryAll().toArray(new borrow[0]);
    }
    @Override
    public borrow[] queryByBook(String book_id) {
        return borrowDaoImp.queryByBook(book_id).toArray(new borrow[0]);
    }
    @Override
    public borrow[] queryByUser(String user_id) {
        return borrowDaoImp.queryByUser(user_id).toArray(new borrow[0]);
    }
    @Override
    public borrow[] queryByBookAndUser(String book_id, String user_id) {
        return borrowDaoImp.queryByBookAndUser(book_id, user_id).toArray(new borrow[0]);
    }
}
